package objects;

import world.BodyID;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.tiled.TiledMap;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;

public class Projectile extends AbstractObject {
	private float startPositionX;
	private final float PROJECTILE_SPEED = 1.0f;

	private final float MAX_TRAVEL_DISTANCE = 30;
	boolean facingRight;

	public Projectile(World _world, Tower _parentTower, boolean _facingRight) {
		this.type = BodyType.DynamicBody;
		this.bullet = true;
		this.position.set(_parentTower.getProjectileStartX(),
				_parentTower.getProjectileStartY());
		facingRight = _facingRight;
		this.gravityScale = 0.0f;

		PolygonShape polygonShape = new PolygonShape();
		Vector2[] vertices = new Vector2[4];

		vertices[0] = new Vector2(-0.16f, 0);
		vertices[1] = new Vector2(0, -0.02f);
		vertices[2] = new Vector2(0.15f, 0);
		vertices[3] = new Vector2(0, 0.02f);
		polygonShape.set(vertices);
		sprite = new Sprite(new Texture(
				Gdx.files.internal("data/sprites/projectile.png")));
		sprite.flip(facingRight, false);

		world = _world;
		body = world.createBody(this);
		body.setUserData(BodyID.PROJECTILE);
		body.setActive(true);
		body.setFixedRotation(true);
		if (facingRight) {

			body.setLinearVelocity(PROJECTILE_SPEED, 0.0f);
		} else {

			body.setLinearVelocity(-PROJECTILE_SPEED, 0.0f);

		}
		FixtureDef fixtureDef = new FixtureDef();
		fixtureDef.shape = polygonShape;
		fixtureDef.friction = 0;
		fixtureDef.isSensor = true;
		body.createFixture(fixtureDef);
	}

	@Override
	public void renderObject(Camera _camera, SpriteBatch _spritebatch) {
		if (body.isActive()) {

			if (facingRight) {
				if (body.getPosition().x - startPositionX >= MAX_TRAVEL_DISTANCE) {
					body.setLinearVelocity(0.0f, 0.0f);
					body.setActive(false);

				}
			}
			sprite.setPosition(
					PIXELS_PER_METER * body.getPosition().x - sprite.getWidth()
							/ 2, PIXELS_PER_METER * body.getPosition().y
							- sprite.getHeight() / 2);
			sprite.draw(_spritebatch);

		}
	}

}
